<?php
// +----------------------------------------------------------------------
// | 供应链
// +----------------------------------------------------------------------
namespace app\schain\model;

use think\Db;
use think\Model;

class SchainEnterpriseModel extends Model {

	protected $type = [
		'more' => 'array',
	];

	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = true;

	/**
	 * 关联 user表
	 * @return $this
	 */
	public function user() {
		return $this->belongsTo('UserModel', 'user_id')->setEagerlyType(1);
	}

	/**
	 * 关联分类表
	 */
	public function categories() {
		return $this->belongsToMany('BusinessCategoryModel', 'schain_category_enterprise', 'category_id', 'ent_id');
	}

	/**
	 * 关联标签表
	 */
	public function tags() {
		return $this->belongsToMany('SchainTagModel', 'schain_tag_enterprise', 'tag_id', 'ent_id');
	}

	/**
	 * ent_content 自动转化
	 * @param $value
	 * @return string
	 */
	public function getEntContentAttr($value) {
		return cmf_replace_content_file_url(htmlspecialchars_decode($value));
	}

	/**
	 * ent_content 自动转化
	 * @param $value
	 * @return string
	 */
	public function setEntContentAttr($value) {
		return htmlspecialchars(cmf_replace_content_file_url(htmlspecialchars_decode($value), true));
	}

	/**
	 * published_time 自动完成
	 * @param $value
	 * @return false|int
	 */
	public function setPublishedTimeAttr($value) {
		return strtotime($value);
	}

	/**
	 * 后台管理添加企业
	 * @param array $data 企业数据
	 * @param array|string $categories 企业分类 id
	 * @return $this
	 */
	public function adminAddEnterprise($data, $categories) {
		$rand = rand(100, 999);
		$time = time();
		$data['ent_no'] = 'qy_' . substr($time, 5) . $rand;

		if (!empty($data['more']['thumbnail'])) {
			$data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
		}

		$this->allowField(true)->data($data, true)->isUpdate(false)->save();

		if (is_string($categories)) {
			$categories = explode(',', $categories);
		}

		$this->categories()->save($categories);

		$data['ent_keywords'] = str_replace('，', ',', $data['ent_keywords']);

		$keywords = explode(',', $data['ent_keywords']);

		$this->addTags($keywords, $this->id);

		return $this;

	}

	/**
	 * 后台管理编辑企业
	 * @param array $data 企业数据
	 * @param array|string $categories 企业分类 id
	 * @return $this
	 */
	public function adminEditEnterprise($data, $categories) {

		unset($data['user_id']);

		if (!empty($data['more']['thumbnail'])) {
			$data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
		}

		$data['ent_status'] = empty($data['ent_status']) ? 0 : 1;
		$data['is_top'] = empty($data['is_top']) ? 0 : 1;
		$data['recommended'] = empty($data['recommended']) ? 0 : 1;

		$this->allowField(true)->isUpdate(true)->data($data, true)->save();

		if (is_string($categories)) {
			$categories = explode(',', $categories);
		}

		$oldCategoryIds = $this->categories()->column('category_id');
		$sameCategoryIds = array_intersect($categories, $oldCategoryIds);
		$needDeleteCategoryIds = array_diff($oldCategoryIds, $sameCategoryIds);
		$newCategoryIds = array_diff($categories, $sameCategoryIds);

		if (!empty($needDeleteCategoryIds)) {
			$this->categories()->detach($needDeleteCategoryIds);
		}

		if (!empty($newCategoryIds)) {
			$this->categories()->attach(array_values($newCategoryIds));
		}

		$data['ent_keywords'] = str_replace('，', ',', $data['ent_keywords']);

		$keywords = explode(',', $data['ent_keywords']);

		$this->addTags($keywords, $data['id']);

		return $this;

	}

	public function addTags($keywords, $articleId) {
		$schainTagModel = new SchainTagModel();

		$tagIds = [];

		$data = [];

		if (!empty($keywords)) {

			$oldTagIds = Db::name('schain_tag_enterprise')->where('ent_id', $articleId)->column('tag_id');

			foreach ($keywords as $keyword) {
				$keyword = trim($keyword);
				if (!empty($keyword)) {
					$findTag = $schainTagModel->where('name', $keyword)->find();
					if (empty($findTag)) {
						$tagId = $schainTagModel->insertGetId([
							'name' => $keyword,
						]);
					} else {
						$tagId = $findTag['id'];
					}

					if (!in_array($tagId, $oldTagIds)) {
						array_push($data, ['tag_id' => $tagId, 'ent_id' => $articleId]);
					}

					array_push($tagIds, $tagId);

				}
			}

			if (empty($tagIds) && !empty($oldTagIds)) {
				Db::name('schain_tag_enterprise')->where('ent_id', $articleId)->delete();
			}

			$sameTagIds = array_intersect($oldTagIds, $tagIds);

			$shouldDeleteTagIds = array_diff($oldTagIds, $sameTagIds);

			if (!empty($shouldDeleteTagIds)) {
				Db::name('schain_tag_enterprise')->where(['ent_id' => $articleId, 'tag_id' => ['in', $shouldDeleteTagIds]])->delete();
			}

			if (!empty($data)) {
				Db::name('schain_tag_enterprise')->insertAll($data);
			}

		} else {
			Db::name('schain_tag_enterprise')->where('ent_id', $articleId)->delete();
		}
	}

}
